package com.terrynoya.fight.commands
{
	import com.terrynoya.coreLib.MHashMap;

	public class CommandManager
	{
		private var _inputBuffer:InputBuffer;
		
		private var _activeCommands:Array;
		
		private var _commandCount:MHashMap;
		
		private var _commands:Array;
		
		public function CommandManager(commands:Array = null)
		{
			this._activeCommands = new Array();
			this._inputBuffer = new InputBuffer();
			this.setCommands(commands);
		}
		
		public function addCommand(cmd:String):void
		{
			this._activeCommands.push(cmd);
		}
		
		public function get inputBuffer():InputBuffer
		{
			return _inputBuffer;
		}

		public function get activeCommands():Array
		{
			return _activeCommands;
		}

		public function setCommands(commands:Array):void
		{
			if(commands == null)
			{
				return;
			}
			this._commands = commands;
			this.initCmdCount(commands);			
		}
		
		private function initCmdCount(commands:Array):void
		{
			this._commandCount = new MHashMap();
			for (var i:int = 0; i < commands.length; i++) 
			{
				var cmd:InputCommand = commands[i];
				this._commandCount.put(cmd.name,new BufferCount());
			}
		}
		
		public function isActive(cmd:String):Boolean
		{
			return this._activeCommands.indexOf(cmd) != -1;
		}
		
		public function update(input:int,facing:int,paused:Boolean):void
		{
			this._inputBuffer.add(input,facing);
			
			if(this._commands == null)
			{
				return;
			}
			if(!paused)
			{
				for (var i:int = 0; i < this._commandCount.length; i++) 
				{
					var bufferCount:BufferCount = this._commandCount.getItemAt(i);
					bufferCount.tick();
				}
			}
			
			this.checkCommands();
			this.createActiveCommands();
		}
		
		public function checkCommands():void
		{
			for (var j:int = 0; j < this._commands.length; j++) 
			{
				var cmd:InputCommand = this._commands[j];
				if(CommandChecker.check(cmd,_inputBuffer))
				{
					var time:int = cmd.bufferTime;
					var bufferCount:BufferCount = this._commandCount.getValue(cmd.name);
					bufferCount.setTime(time);
				}
			}
		}
		
		private function createActiveCommands():void
		{
			this._activeCommands = new Array();
			for (var k:int = 0; k < this._commandCount.keys.length; k++) 
			{
				var key:String = this._commandCount.keys[k];
				var count:BufferCount = this._commandCount.getValue(key);
				if(count.isActive)
				{
					this._activeCommands.push(key);
				}
			}
		}
		
		public function bufferText():String
		{
			return this._inputBuffer.getText();
		}
	}
}